import React, { useReducer, useMemo } from 'react';
import { Form, Table, Button, Divider, Popconfirm, message } from 'antd';
import { useAntdTable } from 'ahooks';
import useEnum from '@/hooks/useEnum';
import Ellipsis from '@/components/Ellipsis';
import { ACTIONS } from './constants';
import { getPositionList, removePosition } from './services';
import TopQueryForm from './components/TopQueryForm';
import PositionModifyDrawer from './components/PositionModifyDrawer';
import styles from './PositionManage.less';

const getTableData = async ({ current, pageSize, sorter }, formData) => {
  const { keyName, isPrimary, orgId } = formData;

  try {
    let params = {
      pageIndex: current,
      pageSize,
      keyName,
      isPrimary,
      orgId,
    };

    if (sorter && JSON.stringify(sorter) !== '{}' && sorter.order) {
      params = {
        ...params,
        sortMap: {
          [sorter.field]: sorter.order === 'ascend' ? 'asc' : 'desc',
        },
      };
    }
    const res = await getPositionList(params);
    const { code, data } = res;
    if (code === 0) {
      return { total: data?.total || 0, list: data?.dataList || [] };
    }
  } catch (e) {
    console.error(e);
  }

  return null;
};

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.ADD:
      return {
        ...state,
        mode: ACTIONS.ADD,
        visible: true,
        position: null,
      };
    case ACTIONS.EDIT:
      return {
        ...state,
        mode: ACTIONS.EDIT,
        visible: true,
        position: action.payload,
      };
    case ACTIONS.CLOSE:
      return {
        ...state,
        visible: false,
      };
    case ACTIONS.PREVIEW:
      return {
        ...state,
        mode: ACTIONS.PREVIEW,
        visible: true,
        position: action.payload,
      };
    default:
      return state;
  }
};

const PositionManage = () => {
  const [form] = Form.useForm();
  // 岗位数据来源字典编码 500
  const dataSourceEnum = useEnum('500');
  const [state, dispatch] = useReducer(reducer, {});

  const { tableProps, search, params } = useAntdTable(getTableData, {
    defaultPageSize: 10,
    form,
  });

  const sorter = useMemo(() => params[0]?.sorter || {}, [params]);
  const { submit, reset } = search;

  const columns = useMemo(
    () => [
      {
        title: '岗位名称',
        dataIndex: 'name',
        width: 200,
        fixed: 'left',
        sorter: true,
        sortOrder: sorter.field === 'name' && sorter.order,
        render: (text) => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '岗位编码',
        dataIndex: 'posCode',
        width: 150,
        fixed: 'left',
        sorter: true,
        sortOrder: sorter.field === 'posCode' && sorter.order,
      },
      {
        title: '所属组织',
        dataIndex: 'orgName',
        width: 200,
        fixed: 'left',
      },
      {
        title: '是否主岗',
        dataIndex: 'isPrimary',
        render: (text) => (text === 1 ? '主岗' : '非主岗'),
        width: 120,
        // sorter: true,
        // sortOrder: sorter.field === 'isPrimary' && sorter.order,
      },
      {
        title: '数据来源',
        dataIndex: 'dataSource',
        width: 150,
        render: (text) => dataSourceEnum.find((item) => item.code === text)?.name || text,
      },
      {
        title: '岗位描述',
        dataIndex: 'description',
        width: 200,
        render: (text) => (
          <Ellipsis length={20} tooltip fullWidthRecognition>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '岗位级别',
        dataIndex: 'posLevel',
        width: 100,
      },
      {
        title: '操作',
        key: 'action',
        width: 160,
        fixed: 'right',
        render: (record) => (
          <div>
            <Button
              style={{ padding: 0 }}
              type="link"
              onClick={() => dispatch({ type: ACTIONS.EDIT, payload: record })}
            >
              编辑
            </Button>
            <Divider type="vertical" />
            <Button
              style={{ padding: 0 }}
              type="link"
              onClick={() => dispatch({ type: ACTIONS.PREVIEW, payload: record })}
            >
              详情
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除该岗位吗？"
              onConfirm={() => {
                removePosition([record.id]).then((res) => {
                  if (res.code === 0) {
                    submit();
                  } else {
                    message.error(res?.message);
                  }
                });
              }}
            >
              <Button style={{ padding: 0 }} type="link">
                删除
              </Button>
            </Popconfirm>
          </div>
        ),
      },
    ],
    [sorter, dataSourceEnum, submit],
  );

  return (
    <div className={styles.root}>
      <TopQueryForm submit={submit} reset={reset} form={form} />
      <div className={styles.bottomWrapper}>
        <div className={styles.rightTable}>
          <div className={styles.rightTableTop}>
            <div className={styles.left}>
              <div className={styles.title}>岗位列表</div>
            </div>
            <div className={styles.right}>
              <Button type="primary" onClick={() => dispatch({ type: ACTIONS.ADD })}>
                新增岗位
              </Button>
            </div>
          </div>
          <div className={styles.tableWrapper}>
            <Table
              {...tableProps}
              columns={columns}
              pagination={{
                ...tableProps.pagination,
                showQuickJumper: true,
                showSizeChanger: false,
                showTotal: (total, range) => `总共${total}条记录，共${Math.ceil(total / 10)}页`,
              }}
              scroll={{ x: 'max-content' }}
            />
          </div>
        </div>
      </div>
      {state.visible && (
        <PositionModifyDrawer
          position={state.position}
          mode={state.mode}
          reloadParent={() => {
            reset();
          }}
          onClose={() => dispatch({ type: ACTIONS.CLOSE })}
          visible={state.visible}
        />
      )}
    </div>
  );
};

export default PositionManage;
